/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package com.googlecode.ivybeans.facade;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.ivy.Ivy;
import org.apache.ivy.core.settings.IvySettings;

/**
 * This singleton class manages ivy extensions as found in a specified directory
 * and configures Ivy instances to look there for extensions.
 * @author Bruce Chapman
 */
public class IvyExtensionsManager {


    private IvyExtensionsManager() {
    }

    private static IvyExtensionsManager instance;

    private List<URL> jars= new ArrayList<URL>();


    public static IvyExtensionsManager getInstance() {
        if(instance == null) {
            instance = new IvyExtensionsManager();
        }
        return instance;
    }

    public void configureExtensions(Ivy ivy) {
        IvySettings settings = ivy.getSettings();
        if(settings == null) {
            settings = new IvySettings();
            ivy.setSettings(settings);
        }
        for(URL jar : jars) {
            settings.addClasspathURL(jar);
        }
    }


    /**
     * Sets the directory where IVY should look for extensions such as IvySVN
     * May be null if no extension directory is defined or needed.
     * @param jarDir The directory where the extension jar files are located.
     */
    public void setExtensionsDir(File jarDir) {
        jars.clear();
        if(jarDir == null) return;
        if(!jarDir.isDirectory()) {
            throw new IllegalArgumentException(jarDir + " is not a directory but must be");
        }
        for(File f : jarDir.listFiles()) {
            if(f.isFile() && f.getName().endsWith(".jar")) {
                try {
                    jars.add(f.toURI().toURL());
                } catch (MalformedURLException ex) {
                    Logger.getLogger(IvyExtensionsManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
